import Radio from 'backbone.radio';
import { ajax_call } from '../../tools.js';

const DuplicableMixin = {
    /**
     * A mixin for models that implement back-end duplication.
     *
     * REST API side has to offer a ?action=duplicate on resource.
     *
     * duplicate() method to the model.
     *
     *
     * Return a promise providing the duplicated model
     *
     *
     *      var promise = this.model.duplicate();
     *      promise.done(function(model){
     *          // Do something with the new model;
     *      })
     *
     * NB : After the promise is resolved, the collection is also up to date
     */
    onDuplicateError: function(result){
        let channel = Radio.channel('message');
        channel.trigger('error:ajax', result);
    },
    onDuplicateCallback: function(result){
        let channel = Radio.channel('message');
        channel.trigger('success:ajax', result);
    },
    duplicate: function(datas, refresh = true){
        // duplication du modèle
        var request = ajax_call(
            this.url() + '?action=duplicate',
            datas,
            'POST'
        );

        let result = request;

        if (refresh) {
            // On chaîne un fetch de la collection
            var collection = this.collection;
            var fetch = request.then(function(){
                return collection.fetch();
            });

            // On crée une promise qui sera résolue si les deux requêtes
            // ci-dessus sont terminées ce qui permet d'avoir toutes les
            // informations lors de la fin de la requête
            let promise = $.when(request, fetch);

            result = promise.then(function(a){
                let model_id = a[0]['id'];
                return collection.get(model_id);
            });
        }

        request.done(
            this.onDuplicateCallback.bind(this)
        ).fail(
            this.onDuplicateError.bind(this)
        );
        return result;
    },
};
export default DuplicableMixin;
